package org.swan;

import javax.print.PrintServiceLookup;
import java.awt.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Properties;

public class MainEntry {
    public static void main(String[] args) throws AWTException, IOException {
        Properties p = new Properties();
        Path path = Paths.get("config.properties");
        if (!path.toFile().exists()) {
            p.put("name", InetAddress.getLocalHost().getHostName());
            p.put("printer", PrintServiceLookup.lookupDefaultPrintService().getName());
            if (System.getenv().containsKey("print.job"))
                p.put("job", System.getenv().get("print.job"));
            p.store(Files.newBufferedWriter(path), "update " + new Date());
        } else {
            p.load(Files.newInputStream(path));
        }
        if (SystemTray.isSupported()) {
            SystemTray tray = SystemTray.getSystemTray();
            PopupMenu popup = new PopupMenu();
            MenuItem aboutItem = new MenuItem("About");
            MenuItem exitItem = new MenuItem("Exit");
            popup.add(aboutItem);
            popup.add(exitItem);
            aboutItem.addActionListener(e -> {
                PrinterSettingFrame.show(p);
                try {
                    p.load(Files.newInputStream(path));
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            });
            exitItem.addActionListener(e -> System.exit(0));
            URL u = MainEntry.class.getClassLoader().getResource("printer.png");
            Image image = Toolkit.getDefaultToolkit().getImage(u);
            TrayIcon icon = new TrayIcon(image, "Printer");
            tray.add(icon);
            icon.setPopupMenu(popup);
        }
    }
}
